// pages/coach-booking/coach-booking.js
const API = require('../../utils/api')
const pathUrl = require('../../utils/common.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    coachId: '',
    courseId: '',
    coachInfo: {},
    dateOptions: [],
    timeSlots: [],
    selectedDate: '',
    selectedTime: '',
    hourOptions: [1, 2, 3, 4, 5], // 可选择的小时数量
    selectedHours: 1, // 默认选择1小时
    unitPrice: 0, // 每小时价格
    totalPrice: 0, // 总价
    loading: false,
    showPaymentModal: false, // 是否显示支付弹窗
    paymentMethod: 'wechat', // 默认支付方式
    paymentSuccess: false // 支付是否成功
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let item = JSON.parse(options.item)
    this.setData({
      coachInfo: item,
      coachId: item.id,
      totalPrice:item.price
    })
    this.generateDateOptions()
  },
  


  /**
   * 生成日期选项
   */
  generateDateOptions() {
    const options = []
    const today = new Date()
    
    // 生成未来7天的日期选项
    for (let i = 0; i < 7; i++) {
      const date = new Date(today)
      date.setDate(today.getDate() + i)
      
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      const weekday = ['日', '一', '二', '三', '四', '五', '六'][date.getDay()]
      
      options.push({
        fullDate: `${year}-${month}-${day}`,
        display: `${month}/${day} 周${weekday}`,
        isToday: i === 0
      })
    }
    
    // 默认选择今天
    this.setData({
      dateOptions: options,
      selectedDate: options[0].fullDate
    })
    
    // 加载对应的时间段
    this.loadTimeSlots(options[0].fullDate)
  },

  /**
   * 加载时间段
   */
  async loadTimeSlots(date) {
    try {
      this.setData({ loading: true })
      
      // 这里模拟时间段数据，实际应该调用API获取
      // 假设教练工作时间为9:00-21:00，每小时一个时段
      const slots = []
      for (let hour = 9; hour <= 20; hour++) {
        const timeStr = `${hour.toString().padStart(2, '0')}:00`
        slots.push({
          time: timeStr,
          available:true
          //available: Math.random() > 0.3 // 70%的概率可预约
        })
      }
      
      this.setData({
        timeSlots: slots,
        selectedTime: ''
      })
    } catch (error) {
      console.error('加载时间段失败:', error)
      wx.showToast({
        title: '加载时间段失败',
        icon: 'none'
      })
    } finally {
      this.setData({ loading: false })
    }
  },

  /**
   * 选择日期
   */
  selectDate(e) {
    const date = e.currentTarget.dataset.date
    this.setData({ selectedDate: date })
    this.loadTimeSlots(date)
  },

  /**
   * 选择时间段
   */
  selectTime(e) {
    const time = e.currentTarget.dataset.time
    this.setData({ selectedTime: time })
  },
  
  /**
   * 选择小时数量
   */
  selectHours(e) {
    const hours = e.currentTarget.dataset.hours
    const totalPrice = this.data.coachInfo.price * hours
    this.setData({
      selectedHours: hours,
      totalPrice: totalPrice
    })
  },
  
  /**
   * 显示支付弹窗
   */
  showPaymentModal() {
    if (!this.data.selectedDate || !this.data.selectedTime) {
      wx.showToast({
        title: '请选择预约日期和时间',
        icon: 'none'
      })
      return
    }
    
    this.setData({
      showPaymentModal: true
    })
  },
  
  /**
   * 关闭支付弹窗
   */
  closePaymentModal() {
    this.setData({
      showPaymentModal: false
    })
  },
  
  /**
   * 选择支付方式
   */
  selectPaymentMethod(e) {
    const method = e.currentTarget.dataset.method
    this.setData({
      paymentMethod: method
    })
  },
  
  /**
   * 模拟支付过程
   */
  async simulatePayment() {
    let form = {coacId:this.data.coachInfo.id,coachName:this.data.coachInfo.name,location:this.data.coachInfo.location,
    price:this.data.totalPrice,bookingDate:this.data.selectedDate,bookingTime:this.data.selectedTime,num:this.data.selectedHours};
    console.log(form)
    API.coachBooking(form).then(res=>{
      wx.showToast({
        title: '预约成功',
        type:'success'
      })
     wx.navigateTo({
       url: '/pages/coach-booking-list/coach-booking-list',
     })
    }).catch(err=>{
      wx.showToast({
        title: '预约失败',
        icon: 'none'
      })
    })
  },

  /**
   * 支付成功后提交预约
   */
  async submitBookingAfterPayment() {
    try {
      this.setData({ loading: true })
      
      // 构建预约数据
      const bookingData = {
        coachId: this.data.coachId,
        courseId: this.data.courseId || '',
        bookingDate: this.data.selectedDate,
        bookingTime: this.data.selectedTime,
        hours: this.data.selectedHours,
        totalPrice: this.data.totalPrice,
        paymentStatus: 'PAID',
        paymentMethod: this.data.paymentMethod
      }
      
      console.log('预约数据:', bookingData)
      
      // 调用预约API
      const res = await API.thirdRequest({
        url: `${pathUrl}/system/coach/booking`,
        method: 'POST',
        data: bookingData
      })
      
      if (res.data.code === 200) {
        wx.showToast({
          title: '预约成功',
          icon: 'success'
        })
        
        // 预约成功后跳转到订单列表页面
        setTimeout(() => {
          wx.navigateTo({
            url: '/pages/orders/orders'
          })
        }, 1500)
      } else {
        wx.showToast({
          title: res.data.message || '预约失败',
          icon: 'none'
        })
        
        // 如果预约失败，关闭支付弹窗
        setTimeout(() => {
          this.closePaymentModal()
        }, 1500)
      }
    } catch (error) {
      console.error('提交预约失败:', error)
      wx.showToast({
        title: '预约失败，请重试',
        icon: 'none'
      })
      
      // 如果预约失败，关闭支付弹窗
      setTimeout(() => {
        this.closePaymentModal()
      }, 1500)
    } finally {
      this.setData({ loading: false })
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})